package cn.circle.system.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.circle.system.dao.ICommodityInfoDao;
import cn.circle.system.model.CommodityInfo;
import cn.circle.system.service.ICommodityInfoService;
import cn.circle.system.model.SysCustomer;
import cn.circle.system.pagemodel.DataGrid;
import cn.circle.system.pagemodel.PageHelper;
import cn.circle.system.util.DateUtils;
import cn.circle.system.util.FtpUtil;
import cn.circle.system.util.HqlHelper;
import cn.circle.system.util.IDUtils;
@Service
public class CommodityInfoServiceImpl implements ICommodityInfoService {
	@Autowired
	private ICommodityInfoDao commodityInfoDao;
	
	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;
	@Value("${FTP_PORT}")
	private String FTP_PORT;
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Value("${IMAGE_BASE_URL}")
	private String IMAGE_BASE_URL;

	@Override
	public boolean save(CommodityInfo commodityInfo,MultipartFile file) {
		// TODO Auto-generated method stub
		if (file != null) {
			
				/*String icon_url = FileUploadUtil.saveFile(file, request,
						getConfigAttr("fileUplaodPath") );*/
				//生成一个新的文件名
				//取原始文件名
				String oldName = file.getOriginalFilename();
				//生成新文件名
				//UUID.randomUUID();
				String newName = IDUtils.genImageName();
				newName = newName + oldName.substring(oldName.lastIndexOf("."));
				//图片上传
				String imagePath = new DateTime().toString("/yyyy/MM/dd");
				try {
					boolean re = FtpUtil.uploadFile(FTP_ADDRESS, Integer.valueOf(FTP_PORT), FTP_USERNAME, FTP_PASSWORD, 
							FTP_BASE_PATH, imagePath, newName, file.getInputStream());
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
				commodityInfo.setPhoto(IMAGE_BASE_URL + imagePath + "/" + newName);			
		}
		commodityInfoDao.save(commodityInfo);
		
		return true;
	}

	@Override
	public List<CommodityInfo> findAll() {
		// TODO Auto-generated method stub
		return commodityInfoDao.find("FROM CommodityInfo");
	}

	@Override
	public boolean deleteAll(String ids) {
		// TODO Auto-generated method stub
		commodityInfoDao.deleteAll(ids);
		return false;
	}

	@Override
	public boolean removeAll(String ids) {
		// TODO Auto-generated method stub
		commodityInfoDao.removeAll(ids);
		return false;
	}

	@Override
	public List<CommodityInfo> getUser(String id) {
		// TODO Auto-generated method stub
		String hql="from CommodityInfo c where c.id="+id;
		List<CommodityInfo> list=commodityInfoDao.find(hql);
		return list;
	}

	@Override
	public boolean update(CommodityInfo commodityInfo,MultipartFile file) {
		// TODO Auto-generated method stub
		if (file != null) {
			try {
				/*String icon_url = FileUploadUtil.saveFile(file, request,
						getConfigAttr("fileUplaodPath"));
				commodityInfo.setPhoto(icon_url);*/
				//生成一个新的文件名
				//取原始文件名
				String oldName = file.getOriginalFilename();
				//生成新文件名
				//UUID.randomUUID();
				String newName = IDUtils.genImageName();
				newName = newName + oldName.substring(oldName.lastIndexOf("."));
				//图片上传
				String imagePath = new DateTime().toString("/yyyy/MM/dd");
				boolean re = FtpUtil.uploadFile(FTP_ADDRESS, Integer.valueOf(FTP_PORT), FTP_USERNAME, FTP_PASSWORD, 
						FTP_BASE_PATH, imagePath, newName, file.getInputStream());

				commodityInfo.setPhoto(IMAGE_BASE_URL + imagePath + "/" + newName);

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		commodityInfoDao.updateAll(commodityInfo);
		return false;
	}

	@Override
	public List<CommodityInfo> getDep() {
		// TODO Auto-generated method stub
		List<CommodityInfo> ll=commodityInfoDao.getDep();
		return ll;
	}

	@Override
	public DataGrid datagrid(PageHelper ph, CommodityInfo c,Double _price, Double price_) {
		// TODO Auto-generated method stub
		DataGrid dg = new DataGrid();
		List<CommodityInfo> cml = new ArrayList<CommodityInfo>();
		//用来放置查询的条件
		Map<String, Object> params = new HashMap<String, Object>();
		
		//注意下面为HQL语句，里面sql的关键字大小写不敏感，其它是敏感的,from后面是model类名称
		StringBuffer hql = new StringBuffer(
				"from CommodityInfo t where 1=1 ");
		
		//以下为查询条件
		if(c.getPrice()!= null && !"".equals(c.getPrice())){
//			Double price;
//			price = c.getPrice();
			System.out.println("价格"+ c.getPrice());
			params.put("price", c.getPrice());
			hql.append(" and t.price =:price ");
		}
		if(c.getNames() != null && !"".equals(c.getNames() )){
			String names = null;
			System.out.println("名字"+ c.getNames());
			try {
				names = URLDecoder.decode(c.getNames() , "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
			params.put("names", "%" +names+ "%");
			hql.append(" and t.names like :names ");
		}
/*		if(c.getStatus() != null && !"".equals(c.getStatus())){
			params.put("status", "%" +c.getStatus() + "%");
			hql.append(" and t.status like :status ");
		}*/
	/*	if(c.getSysDepartment()!= null && !"".equals(c.getSysDepartment()) && c.getSysDepartment().getDepId()!=0){
			params.put("depId",c.getSysDepartment().getDepId());
			hql.append(" and t.sysDepartment.depId = :depId ");
		}*/
//			
		
		if (_price != null && !"".equals(_price)) {
			if (price_ != null && !"".equals(price_)) {
				params.put("_price", _price);
				params.put("price_", price_);
				hql.append(" and t.price >= :_price and t.price <= :price_ ");

			} else {
				params.put("_price", _price);
				hql.append(" and t.price >= :_price ");

			}

		} else {
			if (price_ != null && !"".equals(price_)) {
				params.put("price_", price_);
				hql.append(" and t.price <= :price_ ");

			}
		}
		
		
		
		/*if(depId != null && !"".equals(depId)){
		hql.append("  AND FIND_IN_SET(t.sysDepartment.depId,getChildDepId("+depId+")) > 0 ");
	    }
	*/
		
		//hql = HqlHelper.orderHql(hql, ph); // 排序
		List<CommodityInfo> l = commodityInfoDao.find(hql.toString(), params, ph.getPage(),
				ph.getRows());
		dg.setRows(l);
		dg.setTotal(commodityInfoDao.count("select count(*) " + hql, params));
		return dg;
	}
	
}
